<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/6 0006
 * Time: 下午 4:28
 */

namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class UploaderController extends BaseController
{
    public $file_root_path = 'app/public/';
    public $article_img_path = 'app/public/article/';
    public $return_save_path = '/storage/article/';
    public function imageUploadOne(Request $request)
    {
        if (!$request->hasFile('file')) {
            return ['code'=>1, 'msg'=>'上传文件不存在!',[]];
        }
        $file = $request->file('file');
        if (!$file->isValid()) {
            return ['code'=>1,'msg'=> '文件上传过程中出错,请重新上传!',[]];
        }
        $allowed_extensions = ["png", "jpg", "gif"];
        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
            return ['code'=>1, 'msg'=>'图片上传格式有误,请选择正确的图片!',[]];
        }
        $ext                     = $file->getClientOriginalExtension();

        $save_path               = storage_path($this->article_img_path) . date('Y-m-d');
        $return_save_path = $this->return_save_path.date('Y-m-d');
        $storage_file_name       = uniqid();
        $storage_file_name_thumb = $storage_file_name . '_thumb';
        if ($file->move($save_path, $storage_file_name . '.' . $ext)) {
            Image::make($save_path . DIRECTORY_SEPARATOR . $storage_file_name . '.' . $ext)->resize(100, null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($save_path . DIRECTORY_SEPARATOR . $storage_file_name_thumb . '.' . $ext);
            $data = [
                'img'       => $return_save_path . DIRECTORY_SEPARATOR . $storage_file_name . '.' . $ext,
                'img_thumb' => $return_save_path . DIRECTORY_SEPARATOR . $storage_file_name_thumb . '.' . $ext
            ];
            return ['code'=>0,'msg'=>'图片上传成功!','data'=>$data];
        } else {
            return ['code'=>1,'msg'=> '文件存储失败,请重新上传!',[]];
        }
    }

    public function fileUpload()
    {
        return view('admin.test.fileupload');
    }
}